<template>
  <div class="dataBase">
    <ContentWrap>
      <el-form
        label-width="100px"
        ref="formRef"
        :model="searchValue"
        class="flex flex-wrap"
        v-if="infoShowList && infoShowList.length"
      >
        <el-col :span="6" v-if="infoShowList[6].query">
          <el-form-item label="数据标准" prop="template">
            <el-select
              v-model="searchValue.template"
              clearable
              placeholder="请选择数据标准"
              filterable
            >
              <el-option
                v-for="(template, templateIndex) in templateList"
                :key="templateIndex"
                :label="template.dataStandardName"
                :value="template.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" prop="id" v-if="infoShowList[0].query">
          <el-form-item label="资产id">
            <ns-input v-model="searchValue.id" clearable placeholder="请输入资产id" />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[1].query">
          <el-form-item label="数据源名称" prop="name">
            <ns-input v-model="searchValue.name" clearable placeholder="请输入数据源名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[2].query">
          <el-form-item label="资产IP" prop="ip">
            <ns-input v-model="searchValue.ip" clearable placeholder="请输入资产IP" />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[3].query">
          <el-form-item label="数据库类型" prop="assetType">
            <el-select v-model="searchValue.assetType" clearable placeholder="请选择数据库类型">
              <el-option
                v-for="item in assetTypeList"
                :label="item.showName"
                :key="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[4].query">
          <el-form-item label="库名" prop="dbName">
            <ns-input v-model="searchValue.dbName" clearable placeholder="请输入库名" />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[5].query">
          <el-form-item label="数据库来源" prop="source">
            <el-select v-model="searchValue.source" clearable placeholder="请选择数据库来源">
              <el-option label="在线数据源" :value="1" />
              <el-option label="离线数据源" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[7].query">
          <el-form-item label="归属机构" prop="deptId">
            <el-cascader
              v-model="searchValue.deptId"
              clearable
              placeholder="请选择归属机构"
              :options="options"
              :props="cascaderProps"
              filterable
              :filter-method="sysFilterMethod"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[8].query">
          <el-form-item label="归属系统" prop="sysId">
            <el-cascader
              v-model="searchValue.sysId"
              placeholder="请选择归属系统"
              :props="systemCascaderProps"
              :options="systemList"
              filterable
              :filter-method="sysFilterMethod"
              clearable
          /></el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[9].query">
          <el-form-item label="采样时间" prop="sampleTime">
            <el-date-picker
              v-model="searchValue.sampleTime"
              type="datetimerange"
              range-separator="到"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[10].query">
          <el-form-item label="分级进度" prop="process">
            <el-input
              :min="0"
              :max="100"
              v-model="searchValue.process"
              clearable
              placeholder="请输入分级进度"
              @input="handleInput"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[11].query">
          <el-form-item label="自动分级状态" prop="autoClassStatus">
            <el-select v-model="searchValue.autoClassStatus" clearable placeholder="请选择分级状态">
              <el-option
                v-for="(item, index) in autoClassStatusMap"
                :key="index"
                :label="item[1]"
                :value="item[0]"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[12].query">
          <el-form-item label="自动分级时间" prop="autoClassificationTime">
            <el-date-picker
              v-model="searchValue.autoClassificationTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择日期时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="infoShowList[13]?.query">
          <el-form-item label="审核状态" prop="auditStatus">
            <el-select v-model="searchValue.auditStatus" clearable placeholder="请选择审核状态">
              <el-option label="审核中" :value="1" />
              <el-option label="审核通过" :value="2" />
              <el-option label="审核拒绝" :value="3" />
              <el-option label="待处理" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
      <el-row>
        <el-col :span="24" class="text-right">
          <el-button @click="searchReset" plain>重置</el-button>
          <el-button @click="search" plain>搜索</el-button>
        </el-col>
      </el-row>
    </ContentWrap>
    <ContentWrap>
      <el-form-item>
        <el-button type="primary" @click="uploadAssets" v-hasPermi="['pending:database:upload']">
          上传离线数据文件</el-button
        >
        <el-button
          type="primary"
          :disabled="ids.length == 0"
          @click="openAutoClassification"
          v-hasPermi="['pending:database:autoClass']"
        >
          智能分类分级</el-button
        >
        <el-button
          type="primary"
          :disabled="ids.length == 0"
          @click="handleAuditList"
          v-hasPermi="['pending:database:audit']"
        >
          批量提交审核
        </el-button>
        <el-button
          :disabled="ids.length == 0"
          type="danger"
          @click="delList"
          v-hasPermi="['pending:database:delete']"
        >
          删除
        </el-button>
        <el-button
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['pending:database:export']"
        >
          导出</el-button
        >
        <el-button @click="handleEditInfo" v-hasPermi="['pending:database:showInfo']"
          >信息展示设置</el-button
        >
        <el-button @click="handleShowList" v-hasPermi="['pending:database:showUploadStatus']"
          >查看上传状态</el-button
        >
      </el-form-item>
      <AsyncTable
        v-bind="tableInfo"
        ref="tableRef"
        :fetchData="fetchData"
        @selection-change="changeTable"
      />
    </ContentWrap>
    <InfoShow ref="dialogRef" @success="getInfoShowConf" />
    <DataBaseList
      :dialogVisible="dialogVisible"
      @close="dialogVisible = false"
      v-if="dialogVisible"
      taskBatchNum="**"
    />
  </div>
</template>

<script setup lang="tsx">
import { sysFilterMethod } from '@/utils/selectFilter'
import { ElMessage } from 'element-plus'
import AsyncTable from '@/components/AsyncTable'
import { useRouter } from 'vue-router'
import * as api from '@/api/dataSourceManage/index'
import {
  getDataSourcePage,
  pendingAssetDelete,
  assetSourceExport,
  pendingAssetListDelete,
  assetSourceAuditBatch,
  assetSourceCancel,
  clonePeddingDb
} from '@/api/assetList/index'
import { getSimpleDeptList } from '@/api/system/dept'
import { handleTree } from '@/utils/tree'
import { ComponentInternalInstance, getCurrentInstance } from 'vue'
import { autoClassStatusRender, sourceRender } from '@/utils/commonRender'
import { getSimpleSystemList } from '@/api/asset/taskManage'
import * as infoShowApi from '@/api/infoShow/index'
import InfoShow from '@/views/assetManage/components/infoShow.vue'
import { dataStandardsPage } from '@/api/dataStandards/standards/index'
import { autoClassStatusMap } from '@/utils/dict'
import download from '@/utils/download'
import { checkPermi } from '@/utils/permission'
import { Hide, View } from '@element-plus/icons-vue'
import DataBaseList from '../components/DataBaseList.vue'
const message = useMessage() // 消息弹窗
const systemList = ref([
  {
    id: 1,
    name: '系统1',
    children: [
      { id: 11, name: '子系统1' },
      { id: 12, name: '子系统2' },
      { id: 13, name: '子系统3' }
    ]
  }
])
const systemCascaderProps = {
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
}
const dialogVisible = ref(false)
const tableRef = ref()
const formRef = ref()
const { proxy } = getCurrentInstance() as any
const router = useRouter()
const ids = ref<string[]>([])
const items = ref<any[]>([])
const cascaderProps = ref({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
})
const options = ref<Tree[]>([])
const assetTypeList = ref([])
/**
 * @description: 选取列表时获取列表id
 * @param {*} val
 */
const changeTable = (val) => {
  ids.value = []
  items.value = []
  val.map((item) => {
    ids.value.push(item.id)
    items.value.push(item)
  })
}
const searchReset = () => {
  formRef.value.resetFields()
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
const searchValue = ref({
  id: '',
  name: '',
  ip: '',
  assetType: '',
  dbName: '',
  deptId: '',
  sampleTime: '',
  sysId: '',
  configStatus: '',
  template: '',
  dataSourceName: '',
  auditStatus: '',
  database: '',
  source: '',
  process: undefined,
  autoClassStatus: '',
  autoClassificationTime: '',
  sourceType: ''
})
const allSelect = ref(false)

const search = () => {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}

function checkSelectable(row) {
  return row.auditStatus != '1'
}

const handleShowIp = (row) => {
  row.isShowIp = !row?.isShowIp
}
const handleShowIdIp = (row) => {
  row.isShowIdIp = !row?.isShowIdIp
}
const tableInfo = reactive({
  columns: [
    {
      type: 'selection',
      selectable: checkSelectable
    },
    {
      label: '资产id',
      width: '250px',
      render: ({ row }) => {
        return (
          <>
            <div style="display:flex;align-items:center;justify-content:space-between;">
              {row?.isShowIdIp ? (
                <span>{row.id}</span>
              ) : (
                <span style="font-size:17px">***********</span>
              )}
              {row?.isShowIdIp ? (
                <el-icon>
                  <Hide onClick={() => handleShowIdIp(row)} />
                </el-icon>
              ) : (
                <el-icon>
                  <View onClick={() => handleShowIdIp(row)} />
                </el-icon>
              )}
            </div>
          </>
        )
      }
    },
    {
      label: '数据源名称',
      prop: 'name',
      minWidth: '100px'
    },
    {
      label: '资产IP:端口',
      width: '170px',
      render: ({ row }) => {
        return (
          <>
            <div style="display:flex;align-items:center;justify-content:space-between;">
              {row?.isShowIp ? (
                <span>{row.port ? row.ip + ':' + row.port : row.ip}</span>
              ) : (
                <span style="font-size:17px">***********</span>
              )}
              {row?.isShowIp ? (
                <el-icon>
                  <Hide onClick={() => handleShowIp(row)} />
                </el-icon>
              ) : (
                <el-icon>
                  <View onClick={() => handleShowIp(row)} />
                </el-icon>
              )}
            </div>
          </>
        )
      }
    },
    {
      label: '数据库类型',
      render({ row }) {
        return (
          <>
            <span>{row.assetTypeName || row.assetType}</span>
          </>
        )
      },
      width: '120px'
    },
    {
      label: '库名',
      prop: 'dbName'
    },
    { label: '数据库来源', width: '120px', render: sourceRender },
    {
      label: '数据标准',
      width: '100px',
      prop: 'templateName'
    },
    {
      label: '归属机构',
      width: '100px',
      prop: 'deptName'
    },
    {
      label: '归属系统',
      width: '100px',
      prop: 'sysName'
    },
    {
      label: '采样时间',
      prop: 'sampleTime',
      width: '200px'
    },
    {
      label: '分级进度',
      width: '100px',
      render: ({ row }) => {
        return (
          <>
            <span>{row.process}%</span>
          </>
        )
      }
    },
    {
      label: '自动分级状态',
      width: '120px',
      render: autoClassStatusRender
    },
    {
      label: '自动分级时间',
      prop: 'autoClassificationTime',
      width: '200px'
    },
    {
      label: '创建时间',
      prop: 'createTime',
      width: '200px'
    },
    {
      label: '审核状态',
      width: '100px',
      render: ({ row }) => {
        return (
          <>
            <span>{row.auditStatusValue || '待处理'}</span>
          </>
        )
      }
    },

    {
      label: '操作项',
      width: '300px',
      fixed: 'right',
      render: ({ row }) => {
        return (
          <>
            {checkPermi(['pending:database:clone']) && (
              <el-button
                type="primary"
                link
                onClick={() => {
                  cloneRow(row.id)
                }}
              >
                克隆
              </el-button>
            )}
            {checkPermi(['pending:database:audit']) && (
              <>
                {row.auditStatusValue === '审核中' ? (
                  <el-button
                    link
                    type="primary"
                    onClick={() => {
                      withdrawProcess(row)
                    }}
                  >
                    撤回
                  </el-button>
                ) : (
                  <el-button
                    link
                    type="primary"
                    onClick={() => {
                      submitProcess(row)
                    }}
                  >
                    审核申请
                  </el-button>
                )}
              </>
            )}
            {checkPermi(['pending:database:edit']) &&
              (row.auditStatusValue === '待处理' ||
                row.auditStatusValue === '审核拒绝' ||
                row.auditStatusValue === '--' ||
                !row.auditStatusValue) && (
                <el-button
                  link
                  type="primary"
                  onClick={() => {
                    gotoDetail(row)
                  }}
                >
                  编辑
                </el-button>
              )}

            {checkPermi(['pending:database:history']) && (
              <el-button
                link
                type="primary"
                onClick={() => {
                  goHistory(row)
                }}
              >
                历史记录
              </el-button>
            )}
            {checkPermi(['pending:database:delete']) &&
              (row.auditStatusValue === '待处理' ||
                row.auditStatusValue === '审核拒绝' ||
                row.auditStatusValue === '--' ||
                !row.auditStatusValue) && (
                <ns-button
                  style="margin-left:6px"
                  link
                  type="danger"
                  confirm
                  onClick={() => {
                    del(row)
                  }}
                >
                  删除
                </ns-button>
              )}
          </>
        )
      }
    }
  ],
  data: []
})

// 使用正则表达式只允许输入0-9的数字
function handleInput(value) {
  const filteredValue = value.replace(/[^0-9]/g, '')

  if (filteredValue !== searchValue.value.process) {
    searchValue.value.process = filteredValue
  }
}

const withdrawProcess = (row) => {
  proxy?.$modal
    .confirm(`确定要撤回该流程吗？`)
    .then(async () => {
      await assetSourceCancel({ processInstanceId: row.processInstanceId })
      message.success('操作成功！')
      tableRef.value.resetPage()
      tableRef.value.fetchData()
    })
    .catch(() => {})
}

const submitProcess = (row) => {
  proxy?.$Drawer({
    params: {
      ...row,
      processType: 'database',
      type: row.handClassificationName ? `人工` : row.classificationName ? `自动` : '--',
      callBack: () => {
        tableRef.value.resetPage()
        tableRef.value.fetchData()
      }
    },
    title: `提交审核`,
    size: '40%',
    component: import('../components/process.vue')
  })
}

const openAutoClassification = () => {
  proxy?.$Drawer({
    params: {
      ids: ids.value,
      objectType: 1,
      callBack: () => {
        tableRef.value.resetPage()
        tableRef.value.fetchData()
      }
    },
    title: `添加分级对象`,
    size: '50%',
    component: import('@/views/asset/assetList/components/autoServerClassification.vue')
  })
}

const cloneRow = async (id) => {
  const data = await proxy.$modal.confirm(`确定要克隆选择的资产吗？`)
  if (data) {
    await clonePeddingDb({ id })
    tableRef.value.resetPage()
    tableRef.value.fetchData()
  }
}

const del = (row) => {
  pendingAssetDelete(row.id).then((response) => {
    console.log('response', response)
    tableRef.value.fetchData()
    ElMessage.success('提交成功')
  })
}
const pageParams = ref({
  page: 1,
  pageSize: 10
})
const fetchData = async ({ page, pageSize }) => {
  pageParams.value = {
    page,
    pageSize
  }
  const { data, count } = await getDataSourcePage({
    page,
    pageSize,
    datasourceType: '1',
    submitStatus: '1',
    isWait: true,
    ...searchValue.value
  })
  return { data, count }
}
const gotoDetail = (row) => {
  router.push({
    path: '/assetManage/dataBaseDetail',
    query: {
      id: row.id,
      isPending: '1',
      canAdd: true
    }
  })
}
const goHistory = (row) => {
  router.push({
    path: '/assetManage/reviewHistory',
    query: {
      id: row.id,
      dataType: 'dbSource'
    }
  })
}

// 批量提交审核
const handleAuditList = async () => {
  await message.confirm('确定将所选记录提交审核')
  const data = items.value.map((item) => {
    return {
      assetId: item.id,
      assetType: 'db',
      deptId: item.deptId,
      sysId: item.sysId
    }
  })
  console.log('data', data)
  const res = await assetSourceAuditBatch(data)
  if (res) {
    message.success('操作成功')
    tableRef.value.fetchData()
  }
}

const delList = () => {
  proxy.$modal
    .confirm(`确定要删除所选资产吗？`)
    .then(() => {
      pendingAssetListDelete(ids.value).then((response) => {
        console.log('response', response)
        tableRef.value.fetchData()
        ElMessage.success('删除成功')
      })
    })
    .catch(() => {})
}

const uploadAssets = () => {
  router.push({
    path: '/assetManage/addOfflineData',
    query: {
      jumpType: '2',
      isOffLine: true
    }
  })
}

// 导出
const exportLoading = ref(false)
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await assetSourceExport({
      ...pageParams.value,
      ...searchValue.value,
      datasourceType: '1',
      submitStatus: '1',
      isWait: true,
      ids: ids.value
    })
    download.excel(data, '待确认数据库数据资产.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 添加/修改操作 */
const dialogRef = ref()
const handleEditInfo = () => {
  dialogRef.value.open('4')
}

//展示列表
const handleShowList = () => {
  dialogVisible.value = true
}

const getSystemList = async () => {
  const data = await getSimpleSystemList({})
  systemList.value = handleTree(data, 'id', 'pid')
}

// 获取信息展示
const infoShowList = ref()
const getInfoShowConf = async () => {
  const data = await infoShowApi.infoShowList({
    type: '4',
    language: location.href.indexOf('/en/') >= 0 ? 'en' : ''
  })
  infoShowList.value = data
  data.forEach((item, index) => {
    tableInfo.columns[index + 1].hide = item.show === 0 ? true : false
  })
}

// 获取部门
const getDept = () => {
  getSimpleDeptList().then((res) => {
    options.value = res
  })
}

// 获取资产类型
const getAssetType = () => {
  api.getAssetTypeList({ datasourceType: 1 }).then((res) => {
    assetTypeList.value = res
  })
}

// 数据标准
const templateList = ref([])
const getTemplateList = async () => {
  const { data } = await dataStandardsPage({ page: 1, pageSize: 999, type: 1, status: '1' })
  console.log('data', data)
  templateList.value = data
}

onMounted(() => {
  getSystemList()
  getInfoShowConf()
  getDept()
  getAssetType()
  getTemplateList()
})
</script>

<style lang="scss">
.dataBase {
  .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: inline-flex;
    align-items: center;
    line-height: 23px;
    padding-left: 12px;
  }
  .el-form .el-select {
    width: 100%;
  }
  :deep(.hide-expand .cell) {
    display: none;
  }
  :deep(.el-form .el-cascader) {
    width: 100%;
  }
  :deep(.operate-btn .el-button.is-text) {
    padding: 0 10px 0 0;
  }
  .el-dropdown-link:focus {
    outline: none;
  }
}
</style>
